import { sp, SpriteRenderer } from 'cc';
import { _decorator, Component, Node, Vec3, director, Vec2, v3, CCInteger, Animation, SpriteFrame } from 'cc';
import NSyncLoogPosition from '../../ngame/sync/state/tools/NSyncLoogPosition';
import NSyncPosition from '../../ngame/sync/state/tools/NSyncPosition';
import { AStarManage } from '../manage/AStarManage';
import { AStarInfo } from '../manage/tools/AStarGridTool';
import NWorld2Component from '../ngame/sync/NWorld2Component';
import NSyncRoleDir from '../sync/NSyncRoleDir';

const { ccclass, property } = _decorator;

//玩家显示方向 下 左 上 右
export enum RoleDir{
    DOWN,LEFT,UP,RIGHT
}

@ccclass("IRoleController")
export class IRoleController extends NWorld2Component {
    
    moveQueue:AStarInfo[] = [];
    time:number = 0;
    lastPos:Vec3 = null;
    astar:AStarManage = null;
    
    @property({ type: CCInteger, displayName:'速度'})
    speed:number = 8;

    //历史移动的点
    historyMoveInfos:AStarInfo[] = [];
    //最大存储移动历史数
    maxHistoryMoveNumber:number = 0;

    //限制移动距离
    limitMoveLen:number = 0;

    //攻击目标
    attackTarget;

    //四个方向
    @property({ type: [SpriteFrame], displayName:'四个方向'})
    roleSpriteFinds:SpriteFrame[] = [];

    //玩家图片
    @property({type: SpriteRenderer, displayName: '玩家图片'})
    roleSprite:SpriteRenderer;

    //玩家方向
    _roleDir:RoleDir = RoleDir.DOWN;
    get roleDir(){
        return this._roleDir;
    }
    set roleDir(value:RoleDir){
        this._roleDir = value;

        let sprite = this.roleSpriteFinds[value];
        sprite && (this.roleSprite.spriteFrame = sprite.clone());
    }
    

    //是否正在移动
    get isMove(){
        if(this.moveQueue.length){
            return (this.moveQueue.length - this.limitMoveLen) > 0
        }

        return false;
    }



    onLoad(){

        super.onLoad();
        
        let syncPos = new NSyncPosition(this.node);
        //添加位置同步
        this.addSync(syncPos);
        this.addSync(new NSyncLoogPosition(this.node,syncPos));
        this.addSync(new NSyncRoleDir(this));
        
    }

    start() {

        this.astar = director.getScene().getComponentInChildren(AStarManage);
    }

    //移动玩家
    movePlayer(moveList:AStarInfo[]){

        this.lastPos = this.node.worldPosition.clone();
        this.moveQueue = [];
        let astar = null;
        while(astar = moveList.pop()){
            this.moveQueue.push(astar);
        }

    }


    moveXYPlayer(end:AStarInfo){
        this.movePlayer(this.astar.ToAStar(this.astar.worldToV2(this.node.worldPosition.clone()),this.astar.worldToV2(end.point.worldPos)));
    }

    //移动玩家(世界坐标)
    moveWorldPlayer(world:Vec3){

        console.log(`玩家[${this.nId}] - 开始移动 [${JSON.stringify(world)}]`);

        world = Object.assign(v3(),world)

        let moveList = null;
        this.astar.debugPath(moveList = this.astar.ToAStar3World(this.node.worldPosition.clone(),world));

        //移动玩家
        if(moveList){
            this.movePlayer(moveList);
        }

    }

    //移动玩家(XY)
    moveV2Player(end:Vec2){

        this.movePlayer(this.astar.ToAStar(this.astar.worldToV2(this.node.worldPosition.clone()),end));

    }

    //播放动画
    playAnim(name:string){

        let anim:Animation;
        if(!(anim = this.getComponent(Animation))) return;

        anim.play(name);

    }

    update(deltaTime: number) {

        super.update(deltaTime);

        if(this.moveQueue.length > this.limitMoveLen){

            this.time += (deltaTime * this.speed);

            while(this.time > 1){
                this.node.worldPosition = this.moveQueue[0].point.worldPos.clone();
                this.lastPos = this.node.worldPosition.clone();
                
                if(this.maxHistoryMoveNumber > 0){
                    
                    if(this.historyMoveInfos.length >= this.maxHistoryMoveNumber)
                        this.historyMoveInfos.splice(0,1);
                    this.historyMoveInfos.push(this.moveQueue.shift());

                }else{
                    this.moveQueue.shift();
                }

                this.time -= 1;

            }
            // console.log(this.time);
            // math.lerp((this.lastPos || this.node.worldPosition).clone(), this.moveQueue[0].point.worldPos, ratio))

            if(!this.lastPos)  this.lastPos = this.node.worldPosition.clone();
            // this.moveQueue[0] && (Vec3.lerp(this.lastPos,this.node.worldPosition,this.moveQueue[this.moveQueue.length-1].point.worldPos,deltaTime));
            // console.log(v3(0,0,0).lerp(v3(10,0,0),deltaTime));

            if(this.moveQueue[0]){
                
                this.node.worldPosition = this.lastPos.clone().lerp(this.moveQueue[0].point.worldPos,this.time);

                var angle = Math.atan2((this.lastPos.z - this.moveQueue[0].point.worldPos.z), (this.lastPos.x - this.moveQueue[0].point.worldPos.x))
                //下 左 上 右
                let dirs = [Math.abs(-1.57 - angle),Math.abs(0 - angle),Math.abs(3.14 - angle)  , Math.abs(1.57 - angle) ]

                this.updateDirection(dirs.indexOf(Math.min(...dirs)));

            }

        }
        
    }

    //更新方向
    //下 左 上 右
    updateDirection(index:number){

        this.roleDir = index;

    }

}

